package cn.golxen.blog.redis;

import cn.golxen.blog.commons.rabbitVo.AddRedisCategoriesVo;
import cn.golxen.blog.commons.rabbitVo.AddRedisCountByCategoryOrLabelVo;
import cn.golxen.blog.commons.rabbitVo.DeleteRedisCategoryVo;
import cn.golxen.blog.mapper.CategoryMapper;
import cn.golxen.blog.rabbitMQ.producer.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class CategoryRedis {
    @Autowired
    @Qualifier(value = "taskExecutor")
    private ThreadPoolTaskExecutor poolTaskExecutor;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    Producer producer;

    public Integer getCount(){
        String countStr=redisTemplate.opsForValue().get("category_count");
        if (countStr!=null&&!countStr.isEmpty()){
            log.info("走redis");
            return Integer.valueOf(countStr);
        }else {
            log.info("走mysql");
            Integer count=categoryMapper.getCount();
            poolTaskExecutor.execute(()->{
                producer.categoryProducer(new AddRedisCountByCategoryOrLabelVo(String.valueOf(count),"category"));
            });
            return count;
        }
    }

    public void deleteCategory(){
        producer.categoryProducer(new DeleteRedisCategoryVo());
    }

    public List<String> getCategories(){
        Set<String> set=redisTemplate.opsForZSet().range( "categories",0,-1);
        if (set!=null&&!set.isEmpty()){
//        if (Boolean.TRUE.equals(redisTemplate.hasKey("categories"))){
//            Set<String> set=redisTemplate.opsForZSet().range( "categories",0,-1);
            log.info("走redis");
            return new ArrayList<>(set);
        }else{
            List<String> list=categoryMapper.getCategories();
            poolTaskExecutor.execute(()->{
                producer.categoryProducer(new AddRedisCategoriesVo(list));
            });
            log.info("走MySQL");
            return list;
        }
    }
}
